package com.cetc.nsfx.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeUtility;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.alibaba.fastjson.JSONObject;
import com.cetc.nsfx.security.vo.UserContext;
import com.google.common.reflect.TypeToken;


public class BaseWebUtil{

	

	protected final static Logger log = Logger.getLogger(BaseWebUtil.class);
	

	private static final long serialVersionUID = -7720859705321892189L;
	
	private static Properties p = null;


	protected Map<String , Object> result ;
	
	
	protected Map<String, Object> getMapParams(HttpServletRequest request) {
		Map<String, Object> map=new HashMap<String, Object>();
		Map<String, String[]> requestMap=request.getParameterMap();
		for (String key : requestMap.keySet()) {
			map.put(key, StringUtil.arrayToStr((String [])requestMap.get(key)));
		}
		return map;
	}
	/**
	 * 获得参数
	 * @param param
	 * @return
	 */
	protected String getParam(HttpServletRequest request,String param){
		String value=request.getParameter(param.trim());
		return ("".equals(value)||value==null)?"":value;
	}
	
//	protected Gson getGson(){
//		return new Gson();
//	}
	protected JSONObject getJson(){
		return new JSONObject();
	}
	
	protected String [] getParams(HttpServletRequest request,String param){
		return request.getParameterValues(param);
	}
	protected Integer getIntParam(HttpServletRequest request,String param){
		String integer = request.getParameter(param);
		return (integer == null || integer.trim().equals("")) ? null : Integer.parseInt(integer);
	}
	protected double getDoubleParam(HttpServletRequest request,String param){
		String doublevalue = request.getParameter(param);
		return (doublevalue == null || doublevalue.trim().equals("")) ? 0d : Double.valueOf(doublevalue);
	}
	
	
	protected void outStr(HttpServletResponse response, Boolean b){
		try {
			PrintWriter out = response.getWriter();
			response.setContentType("text/javascript;charset=UTF-8");
			out.print(b);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 打印XML
	 * @param obj
	 */
	protected void outXMLData(HttpServletResponse response,Object obj) {
		try {
			response.setContentType("text/xml;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(obj);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 打印XML
	 * @param str
	 */
	protected void outResponse(HttpServletResponse response,String str) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getOutputStream().write(str.getBytes("utf-8"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	protected void outJSONData(HttpServletResponse response,Object obj){
		try{
			response.setContentType("text/javascript;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(obj);
			//System.out.println(obj);
			out.flush();
			out.close();
		}catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	
	public void outJSONDataFromMap(HttpServletResponse response,Object obj)throws Exception{
		response.setContentType("text/javascript;charset=UTF-8");
		PrintWriter out = response.getWriter();
//		out.print(JSONObject.fromObject(obj).toString());
		out.print(JSONObject.toJSONString(obj));
		out.flush();
		out.close();
	}
	
	public static String getRequestIp(HttpServletRequest request){
	   if (request.getHeader("x-forwarded-for") != null){ 
		   return request.getHeader("x-forwarded-for");
	   }else if(request.getHeader("Proxy-Client-IP") != null){
		   return request.getHeader("Proxy-Client-IP");
	   }else if(request.getHeader("WL-Proxy-Client-IP") != null){
		   return request.getHeader("WL-Proxy-Client-IP");
	   }else
		   return request.getRemoteAddr();
   }
	
	protected Map<String,String>getPaging(Map<String,String>map){
		int inStart=Integer.parseInt(map.get("start"));
		int inLimit=Integer.parseInt(map.get("limit"));
		Map<String,String>retMap=new HashMap<String,String>();
		map.put("start", (inStart + 1)+"");
		map.put("end", ((inStart+inLimit)+""));
		return map;
	}
	
	protected UserContext getUserContext(){
		Subject currentUser = SecurityUtils.getSubject();
		return (UserContext)currentUser.getPrincipal();
	}

	
	 /**
	  * 从配置文件中获取文件路径
	  * @return
	 */
	public Properties getFtpProperties(){
			//获取文件根目录路径
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("file.properties"); 
			if(p!=null){
				return p;
			}
			 p = new Properties();
			try{
			   p.load(inputStream);   
			}catch (IOException e1){ 
				log.error("获取文件存储路径失败"+e1.getMessage());
			}
			return p;
		}
	protected JSONObject getJSONObject(){
		return new JSONObject();
	}
	public void sendJSON(HttpServletResponse response, String json) {
		try {
			response.getOutputStream().write(json.getBytes("UTF-8"));
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public void sendSuccessJSON(HttpServletResponse response) {
		sendJSON(response, "{\"message\":\"success\"}");
	}

	public void sendErrorJSON(HttpServletResponse response){
		sendJSON(response, "{\"message\":\"error\"}");
	}


	public Map<String, Object> getResult() {
		return result;
	}

	public void setResult(Map<String, Object> result) {
		this.result = result;
	}
	
	
	public String encodeFilename(HttpServletRequest request,String fileName)  {
		  String agent = request.getHeader("USER-AGENT");
		  try {
		   // IE
		   if (null != agent && -1 != agent.indexOf("MSIE")) {
		    fileName = URLEncoder.encode(fileName, "UTF8");
		   // Firefox
		   } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
		    fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
		   }
		  } catch (UnsupportedEncodingException e) {
		   try {
		    fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
		   } catch (UnsupportedEncodingException e1) {
		    e1.printStackTrace();
		   }
		   e.printStackTrace();
		  }
		  return fileName;
		 }

}
